package com.loan.controller;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.loan.enums.InvestLogType;
import com.loan.enums.S;
import com.loan.model.Data;
import com.loan.model.Loan;
import com.loan.model.Repay;
import com.loan.model.User;
import com.loan.service.InvestLogService;
import com.loan.service.LoanService;
import com.loan.service.LoggerService;
import com.loan.service.RepayService;
import com.loan.util.DateUtil;
import com.loan.util.Json;
import com.loan.util.Str;

/**
 *  用户控制器
 * @since 2018-03-03
 * @author 无处不在的二叔
 */ 
public class RepayController extends Controller {
	private static LoanService loan = new LoanService();
	private static LoggerService log = new LoggerService(); 
	private static RepayService repay = new RepayService();
	
	/** 
	 * 提前还款
	 */ 
	public void index() { 
		User u = getAttr("user");
		int loanId = getParaToInt("loanId",0);
		int repayId = getParaToInt("repayId",0);
		
		// 单笔还款
		if(repayId>0) {
			Repay rp = Repay.dao.findById(repayId);
			if(rp!=null && rp.getUserId().equals(u.getId()) && Str.eq(S.REPAY_PROCESS, rp.getStatus())) {
				rp.setStatus(S.VERIFY).setCertificatePic(getPara("pic")).setCertificateTime(new Date()).update();
				renderJson(Json.ok("提交成功，信息审核中！"));
			}else{
				renderJson(Json.error("申请记录信息不正确！"));
			}
		}else {	
			Loan ln = null;
			if(loanId==0) {
				ln = loan.findProcess(u.getId());
				if(ln!=null) {
					loanId = ln.getId();
				}
			}else {
				ln = Loan.dao.findById(loanId);
			}
			ln.setReason("信息审核中").update();
			
			//全额还款 
			if(ln!=null && ln.getUserId().equals(u.getId()) && Str.eq(S.REPAY_PROCESS, ln.getStatus())) {
				ln.setStatus(S.REPAY_ADVANCE).setIsAdvance(1).setCertificatePic(getPara("pic")).setCertificateTime(new Date()).update();
				List<Repay> list = repay.findRepayByLoan(loanId, S.REPAY_PROCESS);
				list.forEach(n->{
					n.setStatus(S.REPAY_ADVANCE).setCertificatePic(getPara("pic")).setIsAdvance(1).setCertificateTime(new Date()).update();
				});
				renderJson(Json.ok("提交成功，信息审核中！"));
			}else {
				renderJson(Json.error("申请记录信息不正确！"));
			}
		}
	}	
	
	/**
	 * 确认还款
	 */ 
	public void confirm() { 
		User u = getAttr("user");
		Date now = new Date();
		String status = getPara("status");
		String reason = getPara("reason");
		int loanId = getParaToInt("loanId",0);
		int repayId = getParaToInt("repayId",0);
		String pic = getPara("pic");
		String certificateTime = getPara("certificateTime");
		
		// 单笔还款
		if(repayId>0) {
			Repay rp = Repay.dao.findById(repayId);
			if(Str.nb(pic)) {
				rp.setCertificatePic(pic);
			}
			if(Str.nb(certificateTime)) {
				rp.setCertificateTime(DateUtil.parse(certificateTime));
			}
			if(Str.eq(S.REPAY_SUCCESS, status)) {
				rp.setStatus(S.REPAY_SUCCESS).setRealRepayTime(now).update();
				InvestLogService.build("还款", InvestLogType.REPAY, rp.getPeriodTotal(), rp.getUserId(), "还款");
				if(repay.unSuccess(rp.getLoanId())==null) {
					Loan.dao.findById(rp.getLoanId()).setStatus(S.REPAY_SUCCESS).update();
				}
				InvestLogService.build("还款", InvestLogType.REPAY, rp.getPeriodTotal(), rp.getUserId(), "还款");
				log.build("审核", "单笔还款"+rp.getId()+"审核通过", u.getId(), "backend");
				renderJson(Json.ok("操作成功！"));
			}else if(Str.eq(S.REPAY_PROCESS, status)) {
				rp.setCertificatePic("").setCertificateTime(null).setStatus(S.REPAY_PROCESS).update();
				Loan ln = Loan.dao.findById(rp.getLoanId());
				ln.setReason(reason).update();
				log.build("审核", rp.getId()+"单笔还款审核拒绝，原因："+reason, u.getId(), "backend");
				renderJson(Json.ok("操作成功！"));
			}
		}else{	
			//全额还款
			if(Str.eq(S.REPAY_SUCCESS, status)) { 
				Loan ln = Loan.dao.findById(loanId);
				if(ln!=null) {
					ln.setStatus(S.REPAY_SUCCESS).update();
					List<Repay> list = repay.findRepayByLoan(loanId, S.REPAY_ADVANCE);
					double total = 0.0;
					for(Repay n : list) {
						total += n.getPeriodTotal();
						n.setStatus(S.REPAY_SUCCESS).setRealRepayTime(now).update();
					} 
					InvestLogService.build("还款", InvestLogType.REPAY, total, ln.getUserId(), "还款");
					log.build("审核", ln.getId()+"全额还款审核通过", u.getId(), "backend");
					renderJson(Json.ok("操作成功！"));
				}else {
					renderJson(Json.error("申请记录信息不正确！"));
				}
			}else if(Str.eq(S.REPAY_PROCESS, status)) {
				Loan ln = Loan.dao.findById(loanId);
				if(ln!=null) {
					ln.setRemittance("").setRemittanceTime(null).setStatus(S.REPAY_PROCESS).setReason(reason).update();
					List<Repay> list = repay.findRepayByLoan(loanId, S.REPAY_ADVANCE);
					for(Repay n : list) {
						n.setStatus(S.REPAY_PROCESS).update();
					} 
					log.build("审核", "单笔还款"+ln.getId()+"审核拒绝，原因："+reason, u.getId(), "backend");
					renderJson(Json.ok("操作成功！"));
				}else {
					renderJson(Json.error("申请记录信息不正确！"));
				}
			}
		}
	}	
	
	/**
	 * 编辑分期信息
	 */
	public void divide() {
		Repay rp = Repay.dao.findById(getParaToInt("repayId",0));
		if(rp!=null && (Str.eq(S.REPAY_PROCESS, rp.getStatus()) || Str.eq(S.VERIFY, rp.getStatus())) && (rp.getIsDivide()==0 || rp.getIsDivide()==3) && rp.getPeriod()==1) {
			rp.setCertificatePic(getPara("pic")).setIsDivide(2).update();
			renderJson(Json.ok("操作成功！"));
		}else{
			renderJson(Json.error("状态不正确！"));
		}
	}
	
	/**
	 * 确认分期
	 */
	public void divideConfirm() {
		Repay r = Repay.dao.findById(getParaToInt("repayId",0));
		if(Str.eq(S.REPAY_PROCESS, r.getStatus()) || Str.eq(S.REPAY_DELAY, r.getStatus())) {
			String status = getPara("status","已通过");
			Date now = new Date(); 
			
			if(Str.eq("已通过", status)) {
				r.setDivideTime(now).update();
				r.setId(null).setInterest(Double.valueOf(350)).setCertificatePic(null).setCertificateTime(null).save();
				List<Repay> list = repay.findRepayByLoan(r.getLoanId());
				double total = 0.00;
				for(int i=0; i<list.size(); i++) {
					Repay r1 = list.get(i);
					r1.setPeriod(list.size());
					r1.setApplyPeriod(i+1);
					if(r1.getApplyPeriod()==r1.getPeriod()) {
						r1.setAmount(r.getAmount());
						r1.setStatus("还款中");
						r1.setIsDivide(0);
						r1.setDivideTime(now);
						
						String createTime = DateUtil.adjust(now, 1, DateUtil.DATE_DEFAULT_FORMAT)+" 00:00:00";
						r1.setCreateTime(DateUtil.parse(createTime));
						String repayTime = DateUtil.adjust(now, 7, DateUtil.DATE_DEFAULT_FORMAT)+" 23:59:59";
						r1.setRepayTime(DateUtil.parse(repayTime));
						
						Loan ln = Loan.dao.findById(r1.getLoanId());
						ln.setStartTime(r1.getCreateTime())
							.setEndTime(r1.getRepayTime())
							.setRemittanceTime(r1.getCreateTime())
							.setStatus(S.REPAY_PROCESS)
							.update();
						
					}else {
						r1.setAmount(0);
						r1.setStatus("已结清");
						if(r1.getRealRepayTime()==null) {
							r1.setRealRepayTime(now);
						}
						r1.setIsDivide(1);
					}
					r1.setPeriodTotal(r1.getAmount()+r1.getInterest());
					r1.update();
					total += r1.getPeriodTotal();
				}

				for(int i=0; i<list.size(); i++) {
					list.get(i).setTotal(total).update();
				}

				renderJson(Json.ok("操作成功！"));
	/**
				if(true) {
				}else {
					if(r.getPeriod()==1) {
						
						// 获取请求
						Loan ln = Loan.dao.findById(r.getLoanId());
						ln.setDay(28).update();
						
						// 开始生成还款计划
						int period = ln.getDay()/7;
						User u = User.dao.findById(ln.getUserId());
						double total = 0.0;
						List<Repay> repays = new ArrayList<Repay>();
						for(int i=1;i<=period;i++) {
							Repay rp = new Repay();
							rp.setLoanId(ln.getId());
							rp.setUserId(u.getId());
							rp.setMobile(u.getMobile());
							rp.setRealName(u.getRealName());
							rp.setPeriod(period);
							rp.setApplyPeriod(i);
							if(rp.getApplyPeriod()==rp.getPeriod()) { 
								rp.setAmount(ln.getAmount()-ln.getPledge());
								rp.setPledge(ln.getPledge());
							}else {
								rp.setAmount(0);
								rp.setPledge(0);
							}
							rp.setInterest(Double.valueOf(ln.getInterest()));
							rp.setPeriodTotal(rp.getAmount()+rp.getInterest());
							rp.setCreateTime(new Date());
							rp.setStatus(S.REPAY_PROCESS);
							rp.setCid(ln.getCid());
							rp.setIsDivide(1);
							int adjust = i==1?6:i*7-1;
							String repayTime = DateUtil.adjust(now, adjust, DateUtil.DATE_DEFAULT_FORMAT)+" 23:59:59";
							rp.setRepayTime(DateUtil.parse(repayTime));
							rp.save();
							repays.add(rp);
							
							total += rp.getPeriodTotal();
						}		
						
						// 刷新总额
						for(Repay rp : repays) {
							rp.setTotal(Money.format(total)).update();
						}	
						
						// 删除7天的数据
						r.delete();
						renderJson(Json.ok("操作成功！"));
					}else {
						renderJson(Json.ok("只可拆分单期还款！"));
					}
				}*/
			}else if(Str.eq("已拒绝", status)) {
				r.setIsDivide(3).setDivideReason(getPara("divideReason")).update();
				renderJson(Json.ok("操作成功！"));
			}
		}else {
			renderJson(Json.error("状态不正确！"));
		}
	}
	
	/**
	 * 还款列表
	 */ 
	public void list() { 
		int cid = getAttrForInt("cid");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);		
		String order = getPara("order","field(`status`,'审核中','还款中','已逾期','已结清'), repay_time asc");		
		Map<String,String> params = Data.flat(getParaMap());
		if(cid>1) {
			params.put("cid", String.valueOf(cid));
		}
		Date now = new Date();
		Page<Repay> p = repay.list(page,size,params,order);
		p.getList().forEach(n->{
			n.put("day_gap", DateUtil.diff(n.getRepayTime(), now));
			n.put("count", loan.count(n.getUserId()));
		});
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}	
	
	/**
	 * 手动还款
	 */  
	public void sect() { 
		Repay rp = Repay.dao.findById(getParaToInt("repayId",0));
		if(rp!=null) {
			rp.setIsSect(1).setSectTime(new Date()).setSect(rp.getSect()+getParaToInt("sect")).update();
			if(rp.getSect()>=rp.getPeriodTotal()) {
				rp.setRealRepayTime(new Date()).setStatus(S.REPAY_SUCCESS).update();
				Loan.dao.findById(rp.getLoanId()).setStatus(S.REPAY_SUCCESS).update();
			}
		}
		renderJson(Json.ok("操作成功！"));
	}	
	
	/**
	 * 我的还款列表
	 */ 
	public void myList() { 
		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		int loanId = getParaToInt("loanId",0); 
		String orderBy = getPara("orderBy", "apply_period asc"); 
		if(loanId==0) {
			Loan ln = loan.findProcess(u.getId());
			if(ln!=null) {
				loanId = ln.getId();
			}
		}
		if(loanId>0) {
			Map<String, String> params = Data.flat(getParaMap());
			params.put("userId", String.valueOf(u.getId()));
			params.put("loanId", String.valueOf(loanId));
			Page<Repay> p = repay.list(page,size,params,orderBy);
			renderJson(Json.ok("数据获取成功！", Data.put("page",p, "total", repay.sumByLoan(loanId))));
		}else {
			renderJson(Json.error("暂无订单数据！",loanId));
		}
	}
	
	/**
	 * 根据ID获取信息
	 */
	public void info() throws Exception {	
		Repay rp = Repay.dao.findById(getParaToInt("id",0));
		rp.put("loan", Loan.dao.findById(rp.getLoanId()));
		rp.put("repays", repay.findByUser(rp.getUserId()));
		renderJson(Json.ok("信息获取成功！", rp));
	}  
	
	/**
	 * 编辑还款信息
	 */ 
	public void edit() {   
		Repay rp = Repay.dao.findById(getParaToInt("id",0));
		if(rp!=null) {  
			rp.setTotal(Double.valueOf(getPara("total")));
			rp.setPeriodTotal(Double.valueOf(getPara("periodTotal")));
			rp.setAmount(getParaToInt("amount"));
			rp.setInterest(Double.valueOf(getPara("interest")));
			rp.setPledge(getParaToInt("pledge"));
			rp.update();
			renderJson(Json.ok("还款信息编辑成功！")); 
		}else{
			renderJson(Json.error("还款信息编辑失败！"));
		}
	}
	
}
 